package com.bat.conf.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: datasource配置
 * @Author: zpf
 * @Date: 2020/1/16 下午8:45
 */
@Configuration
public class DataSourceConfig {
    @Value("${mybatis.mapper-locations}")
    private String resources;

    @Bean("localDataSource")
    @ConfigurationProperties("datasource.local")
    public DataSource localDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("remoteDataSource")
    @ConfigurationProperties("datasource.remote")
    public DataSource remoteDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource(@Qualifier("localDataSource") DataSource primaryDataSource,
        @Qualifier("remoteDataSource") DataSource miaoMoreDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DatabaseTypeEnum.LOCAL, primaryDataSource);
        targetDataSources.put(DatabaseTypeEnum.REMOTE, miaoMoreDataSource);

        DynamicDataSource dataSource = new DynamicDataSource();
        // 该方法是AbstractRoutingDataSource的方法
        dataSource.setTargetDataSources(targetDataSources);
        // 默认的datasource设置为myTestDbDataSource
        dataSource.setDefaultTargetDataSource(primaryDataSource);
        return dataSource;
    }

    /*
       不用声明  SqlSessionFactory
     * 根据数据源创建SqlSessionFactory
     */
    //    @Bean
    //    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource)
    //        throws Exception {
    //        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    //        bean.setDataSource(dynamicDataSource);
    //        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(resources));
    //        return bean.getObject();
    //    }

}
